#工作是总资产服务类  flydragon
class Finances::IndexTotalService
  include HeiPisService

  #view 视图上下文
  #company 公司
  def initialize(company)
    @company = company
  end

  #执行方法 返回值
  def call

    # 课消总计
    total_course_reckon = CourseReckon.joins(:studio).where({"studios.company_id"=> @company.id}).sum(:amount).to_f.round(2)
    
    Result.new(get_total_income, total_course_reckon, get_total_expenditure)
  end

  # 收入总计  工工作室维护+工作室订单
  def get_total_income

    amount = 0

    # 订单
    amount += Order.joins(:studio).where({"studios.company_id" => @company.id}).sum(:total_price).to_f
    # 工作室维护
    amount += Finance.where(company_id: @company.id,finance_type: '收入',is_system: 0).sum(:amount)

    amount.round(2)
  end

  # 支出＝ 工作室录入收入 ＋ 固定支出 + 员工薪资
  def get_total_expenditure

    amount = 0

    # 工作室维护
    amount += Finance.where(company_id: @company.id,finance_type: '支出',is_system: 0).sum(:amount)


    # 固定支出
    # 每月的固定支出
    pre_month_amount = FixedCost.joins(:studios).where({"studios.company_id"=> @company.id}).sum("fixed_costs.amount/fixed_costs.cycle")
    amount += months_for_dates(@company.created_at.to_datetime,DateTime.current)*pre_month_amount


    # 员工薪资
    amount += SalaryMonthStatistic.where(company_id: @company.id).sum(:sum_salary)
    amount.round(2)
  end


   #内部类,指定结果返回值
  class Result
    attr_reader :total_income, :total_course_reckon,:total_expenditure,:balance_amonut

    # total_income 收入总计
    # total_course_reckon 课消总计
    # total_expenditure 支出总计
    def initialize(total_income, total_course_reckon, total_expenditure)
      @total_income = total_income
      @total_course_reckon = total_course_reckon
      @total_expenditure = total_expenditure
      @balance_amonut = (total_income-total_expenditure).round(2)
    end 

  end




end
